package org.cogaen.java2d.xml;

import javax.xml.stream.XMLStreamReader;

public class ElementFilter implements ResetableStreamFilter {

	private static final String NAME_SPACE = null;
	private static final String ID_ATTRIB = "id";
	private String name;
	private String id;
	private boolean flag = false;
	
	public ElementFilter(String name, String id) {
		this.name = name;
		this.id = id;
	}
	
	public ElementFilter(String name) {
		this(name, null);
	}
	
	@Override
	public void reset() {
		this.flag = false;
	}

	@Override
	public boolean accept(XMLStreamReader reader) {
		if (this.flag) {
			if (isEnd(reader)) {
				this.flag = false;
			}
			return true;
		} else {
			return this.flag = isStart(reader);
		}			
	}
	
	private boolean isStart(XMLStreamReader reader) {
		if (this.id != null) {
			return reader.isStartElement() && 
				this.name.equals(reader.getLocalName()) && 
				id.equals(reader.getAttributeValue(NAME_SPACE, ID_ATTRIB));			
		} else {
			return reader.isStartElement() && this.name.equals(reader.getLocalName());
		}
	}
	
	private boolean isEnd(XMLStreamReader reader) {
		return reader.isEndElement() && this.name.equals(reader.getLocalName());
	}
	
}
